<template>
  <div class="police-list" :class="{ 'demo-mode': systemModel === 'YS' }">
    <!-- 警情总数  v-if="tabs < 2 || tabs == null"  -->
    <div class="police-total" v-if="isList">
      <span>已找到警情共 {{ top3List.count }}</span>
      <span>去年同期 {{ top3List.yoyCount }}</span>
      <span v-if="top3List.chainPercent">同比：{{ top3List.chainPercent }}%</span>
      <span v-if="top3List.yoyPercent">环比： {{ top3List.yoyPercent }}%</span>
      <span v-for="(item, index) in top3List.xqdwTop3" :key="index" style="margin-right: 8px">
        <span v-show="item.count">
          {{ item.xqdwName }}：{{ item.count }}
          <span>({{ item.percent }}%)</span>
        </span>
      </span>
    </div>
    <a-card class="police-header">
      <a-checkbox @change="onCheckAllChange" :indeterminate="indeterminate" :checked="checkAll">
        本页全选
      </a-checkbox>
      <span style="margin-left: 30px">
        共选中
        <span>{{ allCheckedListTotal }}</span>
        条警情
      </span>
      <div style="float: right">
        <a-button
          v-for="(item, index) in visbleButtonList"
          :key="index"
          :type="item.type"
          :loading="item.loading"
          :disabled="item.disabled"
          style="margin-left: 15px"
          :style="{ background: item.background }"
          @click="item.clickHandle"
        >
          <span
            v-if="item.icon"
            class="iconfont icon-AIjiarengongbiaoqian"
            style="width: 17px; height: 17px; color: #ffff; margin-right: 10px"
          ></span>
          {{ item.name }}
        </a-button>
      </div>
    </a-card>
    <!-- 警情列表 -->
    <a-card class="police-content">
      <a-spin :spinning="loading">
        <a-list item-layout="vertical" size="large" :data-source="listData">
          <template #renderItem="{ item, index }">
            <a-list-item key="item.caseNo">
              <!-- 警情单号 -->
              <a-list-item-meta>
                <template #title>
                  <a-checkbox
                    @change="onCheckChange($event, index)"
                    :checked="item.checked"
                    style="color: #177ddc; font-size: 14px"
                  >
                    <div class="case-item case-inline-item">
                      <span class="case-item-key">警情单号:</span>
                      <span v-html="item.caseNo" class="case-item-value"></span>
                    </div>
                  </a-checkbox>
                </template>
              </a-list-item-meta>
              <!-- 报警内容 -->
              <div class="case-desc-text case-item">
                <span class="case-item-key">报警内容:</span>
                <span
                  class="case-item-value"
                  style="margin-left: 5px"
                  v-html="item.caseDesc"
                ></span>
              </div>
              <!-- 出警情况 -->
              <div class="deal-desc-text case-item">
                <span class="case-item-key">出警情况:</span>
                <a-popover :visible="item.hovered" placement="top">
                  <template #content>
                    <div style="width: 1500px">
                      <a-list item-layout="vertical" size="small" :data-source="dataList">
                        <template #renderItem="{ item }">
                          <a-list-item key="item.caseNo">
                            <!-- 警情单号 -->
                            <a-list-item-meta>
                              <template #title>
                                <div class="case-item case-inline-item">
                                  <span class="case-item-key">警情单号:</span>
                                  <span v-html="item.caseNo" class="case-item-value"></span>
                                  <!-- 智能分类 -->
                                  <div
                                    style="float: right"
                                    v-if="item.classifyName && topicType === 'ai'"
                                  >
                                    <m-tag type="ai">{{ item.classifyName }}</m-tag>
                                  </div>
                                </div>
                              </template>
                            </a-list-item-meta>
                            <!-- 报警内容 -->
                            <div class="case-desc-text case-item">
                              <span class="case-item-key">报警内容:</span>
                              <span
                                class="case-item-value"
                                style="margin-left: 5px"
                                v-html="item.caseDesc"
                              ></span>
                            </div>
                            <!-- 出警情况 -->
                            <div class="deal-desc-text case-item">
                              <span class="case-item-key">出警情况:</span>
                              <span class="case-item-value" v-html="item.dealDesc"></span>
                            </div>
                            <a-row class="extra-text">
                              <a-col :span="8">
                                <div class="case-item">
                                  <span class="case-item-key">报警时间:</span>
                                  <span class="case-item-value" v-html="item.callTime"></span>
                                </div>
                                <div class="case-item">
                                  <span class="case-item-key">事发地址:</span>
                                  <span class="case-item-value" v-html="item.happenAddress"></span>
                                </div>
                              </a-col>
                              <a-col :span="8">
                                <div class="case-item">
                                  <span class="case-item-key">报警电话:</span>
                                  <span class="case-item-value" v-html="item.callPhone"></span>
                                </div>
                                <div class="case-item">
                                  <span class="case-item-key">辖区单位:</span>
                                  <span class="case-item-value" v-html="item.xqdwName"></span>
                                </div>
                              </a-col>
                              <a-col :span="8">
                                <div style="margin: 0px 0" class="jq-type-text case-item">
                                  <span class="case-item-key">接警类别:</span>
                                  <span class="case-item-value" style="color: #1ccaff">
                                    {{ item.callSummaryName }}
                                  </span>
                                </div>
                                <div class="fk-type-text case-item">
                                  <span class="case-item-key">反馈类别:</span>
                                  <span class="case-item-value" style="color: #3191ff">
                                    {{ item.dealSummaryName }}
                                  </span>
                                </div>
                              </a-col>
                            </a-row>
                          </a-list-item>
                        </template>
                      </a-list>
                    </div>
                  </template>
                  <span
                    class="case-item-value"
                    v-html="item.dealDesc"
                    v-on:mouseover="mouseOver($event, index)"
                    @mouseleave="mouseLeave(index)"
                  ></span>
                </a-popover>
              </div>
              <a-row class="extra-text">
                <a-col :span="8">
                  <div class="case-item">
                    <span class="case-item-key">报警时间:</span>
                    <span class="case-item-value" v-html="item.callTime"></span>
                  </div>
                  <div class="case-item">
                    <span class="case-item-key">事发地址:</span>
                    <span class="case-item-value" v-html="item.happenAddress"></span>
                  </div>
                </a-col>
                <a-col :span="8">
                  <div class="case-item">
                    <span class="case-item-key">报警电话:</span>
                    <span class="case-item-value" v-html="item.callPhone"></span>
                  </div>
                  <div class="case-item">
                    <span class="case-item-key">辖区单位:</span>
                    <span class="case-item-value" v-html="item.xqdwName"></span>
                  </div>
                </a-col>
                <a-col :span="8">
                  <div style="margin: 0px 0" class="jq-type-text case-item">
                    <span class="case-item-key">接警类别:</span>
                    <span class="case-item-value" style="color: #1ccaff">
                      {{ item.callSummaryName }}
                    </span>
                  </div>
                  <div class="fk-type-text case-item">
                    <span class="case-item-key">反馈类别:</span>
                    <span class="case-item-value" style="color: #3191ff">
                      {{ item.dealSummaryName }}
                    </span>
                  </div>
                </a-col>
              </a-row>
              <!-- 智能分类 -->
              <div class="ai-type" v-if="item.classifyName && topicType === 'ai'">
                <m-tag type="ai">{{ item.classifyName }}</m-tag>
              </div>
              <template #extra>
                <div class="right-operation">
                  <a-button type="link" @click="showDrawer(item.caseNo)" style="color: #fff">
                    警情详情
                  </a-button>
                  <a-button
                    type="link"
                    @click="showModal(item.caseNo)"
                    style="color: #88a7d7"
                    v-if="item.classifyName && topicType === 'ai'"
                  >
                    智能分类修改
                  </a-button>
                </div>
              </template>
            </a-list-item>
          </template>
        </a-list>
      </a-spin>
    </a-card>
    <!-- 分页 -->
    <a-pagination
      v-if="totalCount"
      show-quick-jumper
      show-size-changer
      v-model:current="curretnParams.page"
      :pageSize="curretnParams.size"
      :total="totalCount"
      @change="onChange"
      @showSizeChange="onShowSizeChange"
      :pageSizeOptions="['10', '20', '30', '50']"
    />
    <!-- 警情详情 -->
    <a-drawer
      title="警情详情"
      :destroyOnClose="destroyOnClose"
      :width="600"
      :visible="visible"
      @close="onClose"
      :body-style="{ paddingBottom: '80px' }"
    >
      <police-details :case-no="caseNoDetails"></police-details>
    </a-drawer>
    <!-- 智能分类修改 -->
    <a-modal
      :destroyOnClose="destroyOnClose"
      v-model:visible="modalVisible"
      title="智能分类修改"
      @ok="handleOk"
    >
      <a-form :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-form-item label="选择分类">
          <a-cascader
            :field-names="{ label: 'name', value: 'code', children: 'children' }"
            v-model:value="formState.newClassifyCode"
            :options="options"
            placeholder="请选择分类"
          />
        </a-form-item>
        <a-form-item label="备注">
          <a-textarea v-model:value="formState.remark" placeholder="请输入备注说明" />
        </a-form-item>
      </a-form>
    </a-modal>
    <a-back-top :target="scrollTarget" />
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, PropType, onMounted, toRaw, watch, computed, reactive } from 'vue';
import { useStore } from 'vuex';
// import scrollIntoView from 'scroll-into-view-if-needed';
import PoliceDetails from '@/components/police-details/index.vue';
import MTag from '@/components/m-tag/index.vue';
import { message } from 'ant-design-vue';
import { Option, PoliceInformationItem, ListParams } from './typing';
import { getRevertClassify } from '@/api/district-monitoring/jurisdiction-list/jurisdiction-details/police-list';
import { post } from '@/utils/request';
import { isNil } from 'lodash';
import { querySummaryInfo } from '@/api/intelligentanalysis/grain';
interface ButtonItem {
  type: string;
  name: string;
  background?: string;
  icon?: string;
  visble?: () => boolean;
  clickHandle?: () => any;
  loading?: boolean;
  disabled?: boolean;
}
export default defineComponent({
  props: {
    // 接口参数
    params: {
      required: true,
      type: Object as PropType<ListParams>,
      default: () => {},
    },
    // 接口地址
    portionUrl: {
      required: true,
      type: String,
    },
    buttonList: {
      required: false,
      type: Array as PropType<Array<ButtonItem>>,
      default: () => [],
    },
    topicType: {
      type: String,
      default: 'ai',
    },
    scrollTarget: {
      type: Function,
      default: () => window,
    },
    tabs: {},
    isList: {
      type: Boolean,
      default: () => false,
    },
  },
  emits: ['change', 'ready', 'setTop3list'],
  setup(props, { emit }) {
    const store = useStore();
    const visible = ref<boolean>(false);
    const destroyOnClose = ref<boolean>(true);
    const caseNoDetails = ref<string>('');
    const modalVisible = ref<boolean>(false);
    const totalCount = ref<number>(0);
    const loading = ref<boolean>(false);
    const curretnParams = ref<any>({ ...toRaw(props.params) });
    const pageSize = computed(() => curretnParams.value.size);

    const systemModel = computed(() => store.getters['user/systemModel']);
    const visbleButtonList = computed(() =>
      props.buttonList.filter(o => {
        return isNil(o?.visble) || o.visble();
      }),
    );
    type CheckedCaseNoMapState = {
      [key: number]: Array<string>;
    };
    const checkedCaseNoMap = ref<CheckedCaseNoMapState>({});

    const indeterminate = ref<boolean>(false);
    const checkAll = ref<boolean>(false);

    const listData = ref<Array<PoliceInformationItem>>([]);

    const formState = reactive({
      newClassifyCode: '',
      remark: '',
    });
    const top3List = ref<any>({});
    //警情列表接口
    const getPoliceList = (type = '') => {
      if (!props.portionUrl) return;
      loading.value = true;
      post(props.portionUrl, curretnParams.value)
        .then(res => {
          if (res.code === 200 && res.data) {
            listData.value = res.data.details.map(item => ({
              ...item,
              checked: false,
            }));
            for (let index = 0; index < listData.value.length; index++) {
              listData.value[index].hovered = false;
            }
            totalCount.value = res.data.count || 0;
            setCurrentCheckedList();
            emit('ready', totalCount.value);
          }
        })
        .catch(err => {
          console.log(err);
        })
        .finally(() => {
          loading.value = false;
          // 仅分页时请求接口滚动条回到顶部
          if (type === 'page') {
            const node = props.scrollTarget();
            node?.scrollTo(0, 0);
          }
        });
    };

    const showDrawer = (caseNo: string) => {
      caseNoDetails.value = caseNo;
      visible.value = true;
    };
    const handlequerySummaryInfo = () => {
      querySummaryInfo(curretnParams.value).then(res => {
        top3List.value = res.data;
        emit('setTop3list', res.data);
      });
    };
    const onClose = () => {
      visible.value = false;
    };
    1;
    // 智能分类options
    const options = ref<Array<Option>>([]);
    const showModal = caseNo => {
      caseNoDetails.value = caseNo;
      store.dispatch(`dictionary/GET_TREE_PARAM`).then(() => {
        options.value = computed(() => store.getters['dictionary/classifyTree']).value;
      });
      modalVisible.value = true;
    };

    //分页
    const onChange = async (pageNumber: number) => {
      curretnParams.value.page = pageNumber;
      checkAll.value = false;
      indeterminate.value = false;
      getPoliceList('page');
    };

    const onShowSizeChange = (current: number, pageSize: number) => {
      curretnParams.value.size = pageSize;
      curretnParams.value.page = 1;
      checkAll.value = false;
      indeterminate.value = false;
      checkedCaseNoMap.value = {};
      getPoliceList('page');
    };

    // 回显checkbox
    const setCurrentCheckedList = () => {
      const currentCheckedList = checkedCaseNoMap.value[curretnParams.value.page] || [];
      listData.value.forEach(o => {
        o.checked = currentCheckedList.includes(o.caseNo);
      });
      let checkedList = listData.value.filter(o => o.checked).map(o => o.caseNo);
      checkAll.value = Boolean(checkedList.length) && checkedList.length === listData.value.length;
      indeterminate.value =
        Boolean(checkedList.length) && checkedList.length < listData.value.length;
    };

    const allCheckedList = computed<Array<string>>(() => {
      let list: Array<string> = [];
      Object.values(checkedCaseNoMap.value).forEach((o: Array<string>) => {
        list = list.concat(o);
      });
      return list;
    });

    const allCheckedListTotal = computed(() => allCheckedList.value.length);

    const handleOk = async () => {
      if (formState.newClassifyCode == '') {
        return;
      }
      const optionsList = reactive({
        revertSource: '1',
        caseNos: caseNoDetails,
        remark: formState.remark,
        newClassifyCode: formState.newClassifyCode.slice(-1).toString(),
        inputClassifyName: '',
      });
      const res = await getRevertClassify(optionsList);
      if (res.code === 200) {
        message.success('修改成功！');
      }
      modalVisible.value = false;
      formState.remark = '';
      formState.newClassifyCode = '';
      getPoliceList();
    };

    const onCheckChange = (e, index: number) => {
      listData.value[index].checked = e.target.checked;
      let checkedList = listData.value.filter(o => o.checked).map(o => o.caseNo);
      const listTotal = listData.value.length;
      const checkedListTotal = checkedList.length;
      indeterminate.value = checkedListTotal !== 0 && listTotal !== checkedListTotal;
      checkAll.value = checkedListTotal !== 0 && listTotal === checkedListTotal;
      checkedCaseNoMap.value[curretnParams.value.page] = checkedList;
      emit('change', allCheckedList.value);
    };
    const onCheckAllChange = e => {
      checkAll.value = e.target.checked;
      indeterminate.value = false;
      listData.value.forEach(o => (o.checked = e.target.checked));
      checkedCaseNoMap.value[curretnParams.value.page] = listData.value
        .filter(o => o.checked)
        .map(o => o.caseNo);
      emit('change', allCheckedList.value);
    };

    const dataList = ref([]);
    const mouseOver = (e, index) => {
      if (e.target.nodeName === 'A') {
        listData.value[index].hovered = true;
        curretnParams.value.inputType = 'caseNo';
        curretnParams.value.inputParams = e.target.innerText;
        post(props.portionUrl, curretnParams.value).then(res => {
          dataList.value = res.data.details;
        });
      } else if (e.path[1].nodeName == 'A') {
        listData.value[index].hovered = true;
        curretnParams.value.inputType = 'caseNo';
        curretnParams.value.inputParams = e.path[1].innerText;
        post(props.portionUrl, curretnParams.value).then(res => {
          dataList.value = res.data.details;
        });
      } else {
        listData.value[index].hovered = false;
      }
    };
    const mouseLeave = index => {
      dataList.value = [];
      listData.value[index].hovered = false;
    };
    const divide = (num1, num2) => {
      let t1, t2, r1, r2;
      try {
        t1 = num1.toString().split('.')[1].length;
      } catch (e) {
        t1 = 0;
      }
      try {
        t2 = num2.toString().split('.')[1].length;
      } catch (e) {
        t2 = 0;
      }
      r1 = Number(num1.toString().replace('.', ''));
      r2 = Number(num2.toString().replace('.', ''));
      let number = (r1 / r2) * Math.pow(10, t2 - t1) * 100;
      return number.toFixed(2) + '%';
    };
    onMounted(() => {
      getPoliceList();
      handlequerySummaryInfo();
    });
    watch(
      () => props.params,
      () => {
        curretnParams.value = { ...toRaw(props.params) };
        checkAll.value = false;
        indeterminate.value = false;
        checkedCaseNoMap.value = {};
        // getPoliceList();
      },
      {
        deep: true,
      },
    );

    return {
      visible,
      showModal,
      indeterminate,
      checkAll,
      modalVisible,
      loading,
      onClose,
      caseNoDetails,
      destroyOnClose,
      onChange,
      onShowSizeChange,
      totalCount,
      listData,
      labelCol: { span: 4 },
      wrapperCol: { span: 15 },
      options,
      allCheckedListTotal,
      handleOk,
      showDrawer,
      onCheckChange,
      onCheckAllChange,
      formState,
      pageSize,
      curretnParams,
      visbleButtonList,
      systemModel,
      mouseOver,
      mouseLeave,
      dataList,
      getPoliceList,
      top3List,
      divide,
      handlequerySummaryInfo,
    };
  },
  components: {
    PoliceDetails,
    MTag,
  },
});
</script>
<style lang="less" scoped>
.police-list {
  // 演示模式
  &.demo-mode {
    .ant-list-item {
      transition: transform 0.3s;
      &:hover {
        font-size: 20px;
        background: #2b2d33;
        border-radius: 18px;
        box-shadow: 0px 0px 10px #e99220;
        // box-shadow: 0px 0px 10px #ccc;
        // box-shadow: 0px 0px 12px #1b81e0;
        transform: scale(1.05);
        .ant-list-item-main {
          .case-desc-text,
          .deal-desc-text {
            font-size: 18px;
          }
          .ant-list-item-meta,
          .extra-text {
            font-size: 16px;
          }
        }
      }
    }
  }
  .police-total span:nth-child(2) {
    margin-left: 10px;
  }
  .police-total span:nth-child(3) {
    margin-left: 28px;
  }
  .police-total span:nth-child(4) {
    margin-left: 10px;
  }

  .police-total span:nth-child(5) {
    margin-left: 24px;
  }

  .police-total {
    margin-right: 50px;
    padding: 10px;
    color: #afb9d2;
    font-weight: 400;
    font-size: 14px;
    .police-total-num {
      padding-right: 5px;
      padding-left: 5px;
      color: @primary-color;
      font-weight: 700;
    }
  }

  // 头部
  :deep(.police-header) {
    height: 56px;
    line-height: 56px;
    border-bottom: none;
    .ant-card-body {
      padding: 0px 24px;
    }
  }
  // 内容列表
  :deep(.police-content) {
    .ant-card-body {
      padding: 2px 24px;
    }
    .case-item {
      &.case-inline-item {
        display: inline-flex;
      }

      display: flex;
      flex-wrap: wrap;
      .case-item-key {
        min-width: 66px;
        padding-right: 4px;
      }
      .case-item-value {
        flex: 1;
      }
    }
  }
  :deep(.ant-list-item-main) {
    position: relative;
    .ai-type {
      position: absolute;
      top: 3px;
      right: -10px;
    }
    .ant-list-item-meta {
      margin-bottom: 0;
    }
  }

  // 报警内容
  .case-desc-text {
    padding-left: 28px;
    color: @text-color;
    font-weight: 600;
    font-size: 14px;
  }
  // 接警内容
  .deal-desc-text {
    padding-left: 28px;
    color: @text-color;
    font-size: 14px;
  }
  // 其他字段
  :deep(.extra-text) {
    padding-top: 4px;
    padding-left: 28px;
    color: @text-color-secondary;
    font-size: 14px;
  }
  // 右侧操作
  .right-operation {
    display: flex;
    flex-direction: column;
    justify-content: center;
    width: 150px;
    height: 100%;
    text-align: left;
    border-left: 1px solid @border-color-split;
  }
  :deep(.ant-pagination) {
    margin-top: 15px;
    text-align: center;
  }
}

:deep(.highlight) {
  color: red;
}
.icon-AIjiarengongbiaoqian:before {
  content: '\e6c8';
}
</style>
